<script setup lang="ts">
import { ref, watch, nextTick, computed } from "vue";
import { ElMessage, ElTree } from "element-plus";
import type { Role } from "@/api/role";
import { getRoleMenus, setRolePermissions } from "@/api/role";
import { getMenuList } from "@/api/menu";
import type { Menu } from "@/api/menu";

const props = defineProps<{
  visible: boolean;
  role?: Partial<Role>;
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "save"): void;
}>();

const menuTreeRef = ref<InstanceType<typeof ElTree>>();
const loading = ref(false);
const menuTree = ref<Menu[]>([]);
const selectedMenus = ref<number[]>([]);
const selectedButtonPerms = ref<Record<number, string[]>>({});
const activeMenuId = ref<number | null>(null);
const defaultProps = {
  children: 'children'
};

// 当前激活的菜单
const activeMenu = computed(() => {
  if (!activeMenuId.value) return null;

  for (const menu of menuTree.value) {
    const found = findMenuById(menu, activeMenuId.value);
    if (found) return found;
  }
  return null;
});

// 获取角色菜单权限
const getMenusForRole = async () => {
  if (!props.role?.id) return;

  loading.value = true;
  try {
    // 获取角色已分配的权限
    const rolePermissionsRes = await getRoleMenus(props.role.id);
    if (rolePermissionsRes.code === 0) {
      console.log('获取到角色权限数据:', rolePermissionsRes.data);

      // 设置已选中的菜单
      const selectedMenuIds = rolePermissionsRes.data.map(item => item.id);
      selectedMenus.value = selectedMenuIds;

      // 提取按钮权限
      const tempButtonPerms: Record<number, string[]> = {};
      rolePermissionsRes.data.forEach(menu => {
        if (menu.selected_auths && menu.selected_auths.length > 0) {
          tempButtonPerms[menu.id] = [...menu.selected_auths];
        }
      });
      selectedButtonPerms.value = tempButtonPerms;

      console.log('已设置的选中菜单:', selectedMenus.value);
      console.log('已设置的按钮权限:', selectedButtonPerms.value);

      // 获取菜单树数据
      const menuRes = await getMenuList();
      if (menuRes.code === 0) {
        console.log('获取到菜单树数据:', menuRes.data);
        menuTree.value = menuRes.data;
      } else {
        ElMessage.error(menuRes.msg || "获取菜单列表失败");
      }
    } else {
      ElMessage.error(rolePermissionsRes.msg || "获取角色权限失败");
    }
  } catch (error) {
    console.error("获取角色菜单权限出错:", error);
    ElMessage.error("获取角色菜单权限失败");
  } finally {
    loading.value = false;
  }
};

// 展开所有节点
const expandAll = () => {
  if (menuTreeRef.value) {
    const nodes = menuTreeRef.value.store.nodesMap;
    Object.keys(nodes).forEach((key) => {
      const node = menuTreeRef.value?.store.nodesMap[key];
      if (node) {
        node.expanded = true;
      }
    });
  }
};

// 全选
const checkAll = () => {
  if (menuTreeRef.value) {
    const allNodes: number[] = [];
    const allButtonPerms: Record<number, string[]> = {};

    const getAllKeys = (data: Menu[]) => {
      data.forEach(item => {
        allNodes.push(item.id);

        // 添加所有按钮权限
        const menuAuths = item.all_auths || [];
        if (menuAuths.length > 0) {
          allButtonPerms[item.id] = [...menuAuths];
        }

        if (item.children && item.children.length > 0) {
          getAllKeys(item.children);
        }
      });
    };

    getAllKeys(menuTree.value);
    allNodes.forEach(id => {
      menuTreeRef.value?.setChecked(id, true, false);
    });

    selectedButtonPerms.value = allButtonPerms;
    handleCheckChange({ checkedKeys: allNodes, halfCheckedKeys: [] });
  }
};

// 清空
const clearAll = () => {
  if (menuTreeRef.value) {
    const allNodes: number[] = [];
    const getAllKeys = (data: Menu[]) => {
      data.forEach(item => {
        allNodes.push(item.id);
        if (item.children && item.children.length > 0) {
          getAllKeys(item.children);
        }
      });
    };
    getAllKeys(menuTree.value);
    allNodes.forEach(id => {
      menuTreeRef.value?.setChecked(id, false, false);
    });
    selectedMenus.value = [];
    selectedButtonPerms.value = {};
  }
};

// 监听visible变化，加载菜单数据
watch(() => props.visible, (val) => {
  if (val && props.role?.id) {
    getMenusForRole();
    nextTick(() => {
      expandAll();
    });
  } else {
    selectedMenus.value = [];
    selectedButtonPerms.value = {};
    menuTree.value = [];
    activeMenuId.value = null;
  }
});

// 保存菜单权限
const handleSave = async () => {
  if (!props.role?.id) return;

  loading.value = true;
  try {
    // 从 Tree 组件中获取选中的菜单 IDs
    const checkedNodes = menuTreeRef.value?.getCheckedNodes();
    const halfCheckedNodes = menuTreeRef.value?.getHalfCheckedNodes();

    // 获取完整选中节点的IDs
    const checkedMenuIds = (checkedNodes || []).map(node => node.id);
    const halfCheckedMenuIds = (halfCheckedNodes || []).map(node => node.id);

    // 合并所有选中的菜单IDs
    const allSelectedMenuIds = [...checkedMenuIds, ...halfCheckedMenuIds];

    console.log('选中的菜单节点:', checkedNodes);
    console.log('所有选中的菜单ID:', allSelectedMenuIds);
    console.log('按钮权限:', selectedButtonPerms.value);

    // 更新 selectedMenus 的值
    if (allSelectedMenuIds.length > 0) {
      selectedMenus.value = allSelectedMenuIds;
    }

    // 检查是否选择了菜单
    if (selectedMenus.value.length === 0) {
      ElMessage.warning("请至少选择一个菜单");
      loading.value = false;
      return;
    }

    // 构建接口所需的请求参数格式
    const permissions = [];

    // 处理选中的菜单和按钮权限
    for (const menuId of selectedMenus.value) {
      const buttonPerms = selectedButtonPerms.value[menuId] || [];
      permissions.push({
        permission_id: menuId,
        auths: buttonPerms
      });
    }

    console.log('提交的数据:', {
      role_id: props.role.id,
      permissions: permissions
    });

    const res = await setRolePermissions({
      role_id: props.role.id,
      permissions: permissions
    });

    if (res.code === 0) {
      ElMessage.success("保存成功");
      emit("update:visible", false);
      emit("save");
    } else {
      ElMessage.error(res.msg || "保存失败");
    }
  } catch (error) {
    console.error("保存角色菜单权限出错:", error);
    ElMessage.error("保存失败");
  } finally {
    loading.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("update:visible", false);
};

// 树节点选中状态变化
const handleCheckChange = (data: any) => {
  if (!data) return;
  const { checkedKeys, halfCheckedKeys } = data;
  selectedMenus.value = [...(checkedKeys || []), ...(halfCheckedKeys || [])];

  console.log('选中状态变化 - 选中的菜单:', selectedMenus.value);
  // 更新按钮权限选择状态
  const selectedMenuIds = new Set([...(checkedKeys || []), ...(halfCheckedKeys || [])]);

  // 移除未选中菜单的按钮权限
  Object.keys(selectedButtonPerms.value).forEach(menuIdStr => {
    const menuId = Number(menuIdStr);
    if (!selectedMenuIds.has(menuId)) {
      // 如果菜单不再被选中，则清除其按钮权限
      console.log('移除未选中菜单的按钮权限:', menuId);
      delete selectedButtonPerms.value[menuId];
    }
  });

  // 确保新选中的菜单也有按钮权限记录（如果有必要）
  selectedMenuIds.forEach(menuId => {
    // 查找菜单节点
    let menuNode = null;
    for (const menu of menuTree.value) {
      const found = findMenuById(menu, menuId);
      if (found) {
        menuNode = found;
        break;
      }
    }

    // 如果是有按钮权限的菜单，但尚未初始化按钮权限选择数据
    if (menuNode && hasButtonPermissions(menuNode) && !selectedButtonPerms.value[menuId]) {
      // 初始化为空数组，表示未选择任何按钮权限
      console.log('为新选中的菜单初始化按钮权限:', menuId);
      selectedButtonPerms.value[menuId] = [];
    }
  });
};

// 处理节点点击
const handleNodeClick = (data: Menu) => {
  activeMenuId.value = data.id;

  // 添加调试信息
  console.log('点击菜单:', data.id, data.title);
  console.log('菜单按钮权限信息:', {
    all_auths: data.all_auths || [],
    auths: data.auths || [],
    meta_auths: data.meta?.auths || []
  });
  console.log('是否有按钮权限:', hasButtonPermissions(data));
  console.log('已选中的按钮权限:', selectedButtonPerms.value[data.id] || []);
};

// 显示按钮权限设置
const hasButtonPermissions = (menu: Menu): boolean => {
  if (!menu) return false;

  // 添加调试信息
  if (activeMenuId.value === menu.id) {
    console.log('检查按钮权限:', menu.id, menu.title, menu.all_auths);
  }

  // 检查多种可能的按钮权限来源
  return (
    (Array.isArray(menu.all_auths) && menu.all_auths.length > 0) ||
    (Array.isArray(menu.auths) && menu.auths.length > 0) ||
    (menu.meta?.auths && Array.isArray(menu.meta.auths) && menu.meta.auths.length > 0)
  );
};

// 获取菜单的按钮权限
const getMenuButtonPerms = (menu: Menu): string[] => {
  if (!menu) return [];

  // 按优先级返回按钮权限
  if (Array.isArray(menu.all_auths) && menu.all_auths.length > 0) {
    return menu.all_auths;
  } else if (Array.isArray(menu.auths) && menu.auths.length > 0) {
    return menu.auths;
  } else if (menu.meta?.auths && Array.isArray(menu.meta.auths)) {
    return menu.meta.auths;
  }

  return [];
};

// 查找菜单项
const findMenuById = (rootMenu: Menu, id: number): Menu | null => {
  if (rootMenu.id === id) {
    return rootMenu;
  }

  if (rootMenu.children && rootMenu.children.length) {
    for (const child of rootMenu.children) {
      const found = findMenuById(child, id);
      if (found) return found;
    }
  }

  return null;
};

// 处理按钮权限变化
const handleButtonPermsChange = (value: string[]) => {
  if (activeMenuId.value !== null) {
    selectedButtonPerms.value[activeMenuId.value] = value;
  }
};
</script>

<template>
  <el-dialog :model-value="visible" @update:model-value="(val) => emit('update:visible', val)"
    :title="`分配菜单 - ${props.role?.name}`" width="850px" @close="handleCancel">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>
    <div v-else class="permissions-container">
      <div class="menu-tree-header">
        <div class="menu-operations">
          <el-button type="primary" size="small" @click="checkAll">全选</el-button>
          <el-button type="danger" size="small" @click="clearAll">清空</el-button>
        </div>
      </div>
      <div class="permissions-content">
        <!-- 左侧菜单树 -->
        <div class="menu-tree-container">
          <el-tree ref="menuTreeRef" :data="menuTree" show-checkbox node-key="id" :props="defaultProps"
            :default-checked-keys="selectedMenus" @check="handleCheckChange" @node-click="handleNodeClick"
            highlight-current>
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span>
                  <el-icon v-if="data.icon || data.meta?.icon" class="menu-icon">
                    <component :is="data.icon || data.meta?.icon" />
                  </el-icon>
                  <span>{{ data.title || data.meta?.title || data.name }}</span>
                  <el-tag v-if="data.status === 1" type="info" size="small" class="menu-tag">禁用</el-tag>
                  <el-tag v-if="hasButtonPermissions(data)" size="small" class="menu-tag" type="success" @click.stop>
                    按钮权限
                  </el-tag>
                </span>
                <span class="menu-path" v-if="data.path">{{ data.path }}</span>
              </div>
            </template>
          </el-tree>
        </div>

        <!-- 右侧按钮权限面板 -->
        <div class="button-perms-container">
          <div v-if="activeMenuId" class="button-perms-panel">
            <div class="button-perms-header">
              <h3>{{ activeMenu?.title || activeMenu?.meta?.title || activeMenu?.name }} - 按钮权限</h3>
            </div>
            <template v-if="hasButtonPermissions(activeMenu)">
              <el-checkbox-group v-model="selectedButtonPerms[activeMenuId]" class="button-list"
                @change="handleButtonPermsChange">
                <el-checkbox v-for="perm in getMenuButtonPerms(activeMenu)" :key="perm" :label="perm" border
                  size="small">
                  {{ perm }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
            <template v-else>
              <div class="no-button-perms">
                该菜单没有按钮权限
              </div>
            </template>
          </div>
          <div v-else class="select-menu-hint">
            <el-empty description="请在左侧选择一个菜单查看按钮权限" />
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.loading-container {
  padding: 20px 0;
}

.permissions-container {
  display: flex;
  flex-direction: column;
  height: 500px;

  .menu-tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-weight: bold;
    color: #606266;

    .menu-operations {
      display: flex;
      align-items: center;
      gap: 8px; // 添加按钮间距
    }

    .menu-description {
      font-size: 12px;
      color: #909399;
      font-weight: normal;
    }
  }

  .permissions-content {
    display: flex;
    flex: 1;
    overflow: hidden;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .menu-tree-container {
      flex: 1;
      padding: 10px;
      overflow: auto;
      border-right: 1px solid #EBEEF5;

      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;

        .menu-icon {
          margin-right: 4px;
          vertical-align: middle;
          color: #409EFF;
        }

        .menu-path {
          font-size: 12px;
          color: #909399;
          margin-left: 8px;
        }

        .menu-tag {
          margin-left: 8px;

          &.el-tag--success {
            cursor: pointer;

            &:hover {
              opacity: 0.8;
            }
          }
        }
      }
    }

    .button-perms-container {
      flex: 1;
      overflow: auto;
      padding: 0;
      background-color: #fafafa;

      .button-perms-panel {
        height: 100%;
        display: flex;
        flex-direction: column;

        .button-perms-header {
          padding: 10px 15px;
          border-bottom: 1px solid #EBEEF5;
          background-color: #f5f7fa;

          h3 {
            margin: 0;
            font-size: 16px;
            color: #303133;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .button-list {
          display: flex;
          flex-wrap: wrap;
          padding: 15px;
          gap: 10px;

          .el-checkbox {
            margin-right: 0;
            margin-bottom: 0;
            transition: all 0.3s;
          }
        }
      }

      .no-button-perms,
      .select-menu-hint {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        color: #909399;
      }
    }
  }
}

// 添加一些响应式调整
@media screen and (max-width: 768px) {
  .permissions-content {
    flex-direction: column;

    .menu-tree-container,
    .button-perms-container {
      width: 100%;
    }

    .menu-tree-container {
      border-right: none;
      border-bottom: 1px solid #EBEEF5;
    }
  }
}

// 增加一些动画效果
.el-checkbox-group {
  .el-checkbox {
    transition: all 0.3s ease;
  }
}

// 自定义滚动条样式
:deep(.el-tree) {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.3);
    border-radius: 3px;

    &:hover {
      background-color: rgba(144, 147, 153, 0.5);
    }
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
  }
}
</style>